package service

import (
	"github.com/cn-ygf/go-admin/internal/modular/system/dao"
	"github.com/cn-ygf/go-admin/internal/modular/system/model"
	"github.com/cn-ygf/go-admin/internal/modular/system/vo"
	"github.com/cn-ygf/go-admin/pkg/utils"
	"github.com/kataras/iris/v12"
	"time"
)

var (
	LoginLogService = new(loginLogService)
)

// loginLogService 登录日志管理
type loginLogService struct {
}

func (s loginLogService) GetList() ([]*model.SysLoginLog, error) {
	return dao.SysLoginLog.Where(dao.SysLoginLog.Status.Eq("0")).Find()
}

// QueryList 分页查询登录日志列表
func (s loginLogService) QueryList(req *vo.QueryLoginLogListReq) ([]*model.SysLoginLog, int64, error) {
	var (
		u = dao.SysLoginLog
		d = u.Where()
	)
	if req.PageSize < 1 {
		req.PageSize = 10
	}
	if req.PageNum < 1 {
		req.PageNum = 1
	}
	if req.Ipaddr != "" {
		d = d.Where(u.Ipaddr.Eq(req.Ipaddr))
	}
	if req.UserName != "" {
		d = d.Where(u.UserName.Eq(req.UserName))
	}
	if req.Status != "" {
		d = d.Where(u.Status.Eq(req.Status))
	}
	if req.Params != nil {
		if req.Params.BeginTime > 0 && req.Params.EndTime > 0 {
			d = d.Where(u.LoginTime.Gte(req.Params.BeginTime))
			d = d.Where(u.LoginTime.Lte(req.Params.EndTime))
		}
	}
	return d.FindByPage((req.PageNum-1)*req.PageSize, req.PageSize)
}

// Export 条件查询数据（不分页）
func (s loginLogService) Export(req *vo.ExportLoginLogReq) ([]*model.SysLoginLog, error) {
	var (
		u = dao.SysLoginLog
		d = u.Where()
	)
	if req.Ipaddr != "" {
		d = d.Where(u.Ipaddr.Eq(req.Ipaddr))
	}
	if req.UserName != "" {
		d = d.Where(u.UserName.Eq(req.UserName))
	}
	if req.Status != "" {
		d = d.Where(u.Status.Eq(req.Status))
	}
	if req.Params != nil {
		if req.Params.BeginTime > 0 && req.Params.EndTime > 0 {
			d = d.Where(u.LoginTime.Gte(req.Params.BeginTime))
			d = d.Where(u.LoginTime.Lte(req.Params.EndTime))
		}
	}
	return d.Find()
}

// All 查询所有登录日志
func (s loginLogService) All() ([]*model.SysLoginLog, error) {
	return dao.SysLoginLog.Find()
}

// GetByID 根据id查询登录日志
func (s loginLogService) GetByID(id int64) (*model.SysLoginLog, error) {
	return dao.SysLoginLog.Where(dao.SysLoginLog.InfoID.Eq(id)).First()
}

// Add 添加登录日志
func (s loginLogService) Add(username string, status string, msg string, ctx iris.Context) error {
	u := dao.SysLoginLog
	newPost := &model.SysLoginLog{
		UserName:      username,
		Ipaddr:        utils.GetClientIP(ctx),
		LoginLocation: "",
		UserAgent:     utils.GetUserAgent(ctx),
		Status:        status,
		Msg:           msg,
		LoginTime:     time.Now().Unix(),
	}
	err := u.Create(newPost)
	if err != nil {
		systemLog.Errorln(err.Error())
		return DatabaseError
	}
	return nil
}

// Delete 删除登录日志
func (s loginLogService) Delete(ids []int64) error {
	_, err := dao.SysLoginLog.Where(dao.SysLoginLog.InfoID.In(ids...)).Delete()
	return err
}

// Clean 清空日志
func (s loginLogService) Clean() error {
	_, err := dao.SysLoginLog.Where(dao.SysLoginLog.InfoID.Neq(0)).Delete()
	if err != nil {
		systemLog.Errorln(err.Error())
		return DatabaseError
	}
	return err
}
